package com.mexico.inloancash.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.bean.Mexico_Opinion_Bean;
import com.mexico.inloancash.dialog.PhotoDialog;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.utils.Auth;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;
import com.mexico.inloancash.utils.MyUtils;
import com.mexico.inloancash.utils.permission.Permission;
import com.mexico.inloancash.utils.permission.RxPermissions;
import com.mexico.inloancash.utils.permission.SchedulerTransformer;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UploadManager;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;

public class Mexico_FeedBackActivity extends BaseActivity implements IndiaDealDialogInterface {
    @BindView(R.id.logon_back)
    ImageView logonBack;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.opinion)
    EditText opinion;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.opinion_email)
    EditText opinionEmail;
    private Mexico_Opinion_Bean bean;
    private String imageUrl = "";
    private UploadManager uploadManager;
    private Recorder recorder;
    private KeyGenerator keyGen;
    Configuration config;
    private String upToken;

    String accessKey = "lb5ntuPzvl6BoSqL5yato8Pqwg5WXoPHGVzTktIt";

    String secretKey = "7i3g_SDTFCvJ-TYs3FBfCJJtki8Rp2hYfNVIK908";

    String bucket = "ynimage001";
    //String bucket = "north-us";



    /**
     * 调起拍照
     */
    private File currentImageFile;
    Uri uri;
    private File file = null;
    File zhengFile = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);
        title.setText(getString(R.string.feed));
        bean = new Mexico_Opinion_Bean();
        MyApplication.getInstance().addActivity(this);
        config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .recorder(null)           // recorder分片上传时，已上传片记录器。默认null
                .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zoneAs0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        Auth auth = Auth.create(accessKey, secretKey);
        upToken = auth.uploadToken(bucket);
        opinion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                setButton();
                count.setText(charSequence.length() + "/200");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        opinionEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                setButton();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @OnClick({R.id.logon_back, R.id.image, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.logon_back:
                MyApplication.getInstance().removeActivity(this);
                break;
            case R.id.image:
                new RxPermissions(this)
                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)
                        .compose(new SchedulerTransformer<>())
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                PhotoDialog dialog1 = new PhotoDialog(this, this);
                                dialog1.show();
                            } else {
                                MyToast.show(this, "Por favor, active la lectura/escritura de la tarjeta de memoria, el acceso a la cámara");
                            }
                        });

                break;
            case R.id.submit:
                setEmpty();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyApplication.getInstance().removeActivity(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    public void setOpinion() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> opinion1 = api.opinion(
                MyPreferencesManager.getString("token",""),
                opinion.getText().toString().trim(),
                imageUrl,
                opinionEmail.getText().toString().trim(),
                MyApplication.source);
        opinion1.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                loading.dismiss();
                if(response.isSuccessful()){
                    BaseBean baseBean = new Gson().fromJson(response.body(),BaseBean.class);
                    if(baseBean.getCode() == 200){
                        MyToast.show(Mexico_FeedBackActivity.this,"Submit Successful");
                        finish();
                    }else if(baseBean.getCode() == 401){
                         //MyApplication.getInstance().logOut(FeedBackActivity.this);
                        //MyToast.show(FeedBackActivity.this,"Submit Successful");
                        finish();
                    }else {
                        MyToast.show(Mexico_FeedBackActivity.this,baseBean.getMsg());
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }

    @Override
    public void doPlay() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        camera();
                    } else {
                        MyToast.show(this, getString(R.string.permission));
                    }
                });
    }

    @Override
    public void choose() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<Boolean>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 1);
                    } else {
                        MyToast.show(this, getString(R.string.permission));
                    }
                });
    }

    /**
     * 调取拍照
     */
    public void camera() {
        File dir = new File(getFilesDir(), "myimage");//在sd下创建文件夹myimage；Environment.getExternalStorageDirectory()得到SD卡路径文件
        if (!dir.exists()) {    //exists()判断文件是否存在，不存在则创建文件
            dir.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        String filename = df.format(new Date());
        currentImageFile = new File(dir, filename + ".jpg");
        if (!currentImageFile.exists()) {
            try {
                currentImageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT < 24) {
            currentImageFile = new File(dir, filename + ".jpg");
            // 从文件中创建uri
            uri = Uri.fromFile(currentImageFile);

        } else {
            // 兼容Android 7.0 使用共享文件的形式
            ContentValues contentValues = new ContentValues();
            uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://文件中选择照片
                if (data == null) {
                    return;
                }
                uri = data.getData();
                file = new File(MyUtils.getPath(uri, this));
                loading.show();
                Avatar();
                break;
            case 2://拍照完成回调
                if (Build.VERSION.SDK_INT < 24) {
                    if (null == currentImageFile) {
                        return;
                    }
                    file = currentImageFile;
                } else {
                    file = new File(MyUtils.getPath(uri, this));
                    if (null == file) {
                        return;
                    }
                }
                loading.show();
                Avatar();
                break;
        }
    }

    public void Avatar() {

        if(file==null){
            return;
        }
        String filePath = file.getAbsolutePath();
        if (TextUtils.isEmpty(filePath)) {
            loading.dismiss();
            Toast.makeText(this, "path error", Toast.LENGTH_SHORT).show();
            return;
        }
        //Log.e("data","===Avatar2==="+file.getAbsolutePath());
        List<String> photos = new ArrayList<>();
        photos.add(filePath);
        Flowable.just(photos)
                .observeOn(Schedulers.io())
                .map(new Function<List<String>, List<File>>() {
                    @Override
                    public List<File> apply(@NonNull List<String> list) throws Exception {
                        // 同步方法直接返回压缩后的文件
                        if (list.size() > 0) {
                            String path = Luban.with(Mexico_FeedBackActivity.this).load(list).get().get(0).getAbsolutePath();
                            File file = new File(path);
                            zhengFile = file;
                            Mexico_FeedBackActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.with(Mexico_FeedBackActivity.this).load(zhengFile).placeholder(R.mipmap.yhl_icon_add_pic).into(image);
                                    loading.dismiss();
                                    setButton();
                                }
                            });
                        } else {
                            loading.dismiss();
                        }
                        return Luban.with(Mexico_FeedBackActivity.this).load(list).get();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

       /* //新建一个File，传入文件夹目录
        //File file1 = new File(Environment.getExternalStorageDirectory(), "myshenfen");
        File file1 = new File(getFilesDir(), "mywork");
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file1.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            file1.mkdirs();
        }
        Luban.with(this)
                .load(file)
                .ignoreBy(20)
                .setTargetDir(file1.getPath())
                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(final File file) {
                        zhengFile = file;
                        Glide.with(Mexico_FeedBackActivity.this).load(zhengFile).placeholder(R.mipmap.yhl_icon_add_pic).into(image);
                        loading.dismiss();
                        setButton();
                    }

                    @Override
                    public void onError(Throwable e) {
//                        Debug.e("onError--------" + e.getLocalizedMessage());
                        // TODO 当压缩过程出现问题时调用
                        loading.dismiss();
                    }
                }).launch();*/
    }

    /**
     * 判断未填项
     */

    public void setEmpty(){
        if(TextUtils.isEmpty(opinion.getText().toString().trim())){
            MyToast.show(this,getString(R.string.please_fill_in_the_information));
            return;
        }
        if(TextUtils.isEmpty(opinionEmail.getText().toString().trim())){
            MyToast.show(this,getString(R.string.please_fill_in_the_information));
            return;
        }
        loading.show();
        String token = upToken;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key1 = "icon_3" + sdf.format(new Date());
        uploadManager = new UploadManager(config);
        File myFile = zhengFile;
        uploadManager.put(myFile, key1, token,
                (key, info, res) -> {
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK()) {
                        imageUrl = key;
                        if (TextUtils.isEmpty(imageUrl)) {
                            return;
                        }
                        bean.setEmail(opinionEmail.getText().toString().trim());
                        bean.setImg(imageUrl);
                        bean.setOpinoin(opinion.getText().toString().trim());
                        setOpinion();
                    } else {
                        loading.dismiss();
                        MyToast.show(this,"Image upload failed, please check network connection");
                        //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                    }
                }, null);
    }

    /**
     * 设置按钮变色
     */
    public void setButton() {
        if (TextUtils.isEmpty(opinion.getText().toString().trim())) {
            submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(opinionEmail.getText().toString().trim())) {
            submit.setSelected(false);
            return;
        }
        submit.setSelected(true);
    }
}
